package com.mrd.gtimp.service.client;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.mrd.framework.utils.SpringUtils;
import com.mrd.gtimp.business.entity.Commodity;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.order.entity.DeclaContainer;
import com.mrd.gtimp.service.dto.CTMSBGInfoDTO;
import com.mrd.gtimpframe.repository.UserMapper;
import com.mrd.webservices.yxt.imp.IyxtServices;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lenovo on 2017/10/25.
 */
public class CtmsServiceClient {

    JaxWsProxyFactoryBean factory;
    private Logger logger = LoggerFactory.getLogger(CtmsServiceClient.class);

    public CtmsServiceClient() throws Exception {
        String url = SpringUtils.getBean(Environment.class).getProperty("ctms.ws.url");
        if (StringUtils.isEmpty(url)) {
            throw new Exception("配置文件缺少CTMS接口地址");
        }
        factory = new JaxWsProxyFactoryBean();
        factory.getInInterceptors().add(new LoggingInInterceptor());
        factory.getOutInterceptors().add(new LoggingOutInterceptor());
        factory.setAddress(url);

    }

    public String sendBGInfo(Declaration declaration, String reqUser) throws Exception {
        if (declaration != null) {
            List<Commodity> commodityList = declaration.getCommodities();
            if (CollectionUtils.isEmpty(commodityList)) {
                throw new Exception("没有商品信息");
            }
            Commodity commodity = commodityList.get(0);
            CTMSBGInfoDTO bgInfoDTO = new CTMSBGInfoDTO();
            bgInfoDTO.setGoodsDesc(commodityList.size() > 1 ? commodity.getName() + "等" : commodity.getName());
            bgInfoDTO.setGoodsType(declaration.getGoods_package() + "(" + this.getGoodsTypeCode(declaration.getGoods_package()) + ")");
            bgInfoDTO.setPkgsNum(declaration.getGoods_count());
            bgInfoDTO.setGrossWeight(declaration.getGross_weight());
            bgInfoDTO.setShipper(declaration.getCompany_name());
            bgInfoDTO.setBookingNo(declaration.getSo());
            bgInfoDTO.setBgCompany(this.getBGCompanyId(declaration.getSupCompany().getName()));
            bgInfoDTO.setCiqNo(declaration.getSno());
            bgInfoDTO.setConsignee(declaration.getCustomer().getName());
            bgInfoDTO.setIoType(declaration.getDeclaration_type());
            bgInfoDTO.setReqNo(declaration.getId());
            bgInfoDTO.setReqUser(reqUser);
            List<DeclaContainer> declaContainer = declaration.getDeclaContainers();
            List<String> ctList = new ArrayList<>();
            for (DeclaContainer container : declaContainer) {
                ctList.add(container.getContainerNo());
            }
            bgInfoDTO.setCtList(ctList);
            bgInfoDTO.setStatus("1".equals(declaration.getConfirmType()) ? "1" : "0"); //确认状态
            bgInfoDTO.setZgNo("转关".equals(declaration.getData_type()) ? declaration.getTransport_na() : ""); //转关纸号
            if (StringUtils.isNotEmpty(declaration.getWorkNo())) {
                bgInfoDTO.setWorkNo(declaration.getWorkNo());
            }
            bgInfoDTO.setBlNo(declaration.getBl_no());

            String json = "[" + JSON.toJSONString(bgInfoDTO, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty) + "]";
            //            IyxtServicesImpService impService = new IyxtServicesImpService();
            //            String result = impService.getIyxtServicesImpPort().sendBGInfo(json);
            IyxtServices services = factory.create(IyxtServices.class);
            String result = services.sendBGInfo(json);
            logger.warn("推送三联单信息：" + declaration.getBusinessId() + ", 输入：" + json + ", 结果为：" + result);
            return result;
        }
        throw new Exception("没有查到该报关单");
    }

    /**
     * 推送报关单信息
     */
    public String sendBGInfo(Declaration declaration) throws Exception {
        return sendBGInfo(declaration, null);
    }

    /**
     * 根据报关公司名称获取对应的报关id号
     */
    private String getBGCompanyId(String companyName) throws Exception {
        if (StringUtils.isEmpty(companyName)) {
            throw new Exception("传入报关行名称为空");
        }
        if ("广东中衡报关有限公司佛山新港营业部".equals(companyName)) {
            return "10010990";
        } else if ("佛山市汇联报关有限公司".equals(companyName)) {
            return "10011020";
        } else if ("佛山市佛港报关有限公司".equals(companyName)) {
            return "10006820";
        } else if ("佛山市口岸报关有限公司".equals(companyName)) {
            return "10005770";
        } else if ("佛山市中恒报关有限公司".equals(companyName)) {
            return "10023300";
        } else if ("佛山市口岸报关有限公司南海分公司".equals(companyName)) {
            return "10023500";
        } else if ("广东中衡报关有限公司".equals(companyName)) {
            return "10010991";
        } else if ("广东滨利报关服务有限公司".equals(companyName)) {
            return "100241700";
        } else if ("广东中外运报关有限公司".equals(companyName)) {
            return "10017614";
        } else if ("佛山市南海区中南报关有限公司".equals(companyName)) {
            return "100241740";
        } else if ("佛山市天晟报关有限公司南沙分公司".equals(companyName)) {
            return "100244430";
        } else if ("佛山市易迅通报关有限公司".equals(companyName)) {
            return "100241710";
        } else if ("佛山中外运快件管理报关有限公司".equals(companyName)) {
            return "1002450940";
        }
        throw new Exception("没有该报关行");
    }


    /**
     * 根据包装种类获取包装种类代码
     */
    private String getGoodsTypeCode(String goodsType) {
        if (StringUtils.isEmpty(goodsType)) {
            return null;
        }
        if ("木箱".equals(goodsType)) {
            return "1";
        } else if ("纸箱".equals(goodsType)) {
            return "2";
        } else if ("桶装".equals(goodsType)) {
            return "3";
        } else if ("散装".equals(goodsType)) {
            return "4";
        } else if ("集装箱".equals(goodsType)) {
            return "5";
        } else if ("包".equals(goodsType)) {
            return "6";
        } else if ("其它".equals(goodsType)) {
            return "7";
        } else if ("扎".equals(goodsType)) {
            return "8";
        } else if ("件".equals(goodsType)) {
            return "9";
        } else if ("托盘".equals(goodsType)) {
            return "10";
        }
        return null;
    }

    /**
     * 获取驳船信息
     *
     * @param reqNo 报关单id
     */
    public String getShipInfo(String reqNo) {
        try {
            //IyxtServicesImpService impService = new IyxtServicesImpService();
            IyxtServices services = factory.create(IyxtServices.class);
            String result = services.getShipInfo(reqNo);
            return result;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    /**
     * CTMS接口【更新报关单号】
     *
     * @param reqNo 报关单ID
     * @param sno   报关单号
     */
    public String updateSno(String reqNo, String sno) {
        if (StringUtils.isAnyEmpty(reqNo, sno)) {
            logger.error("CTMS接口【更新报关单号】：未更新成功，传入了空的参数。");
            return "2";
        }
        IyxtServices services = factory.create(IyxtServices.class);
        String format = "{\"ciqNo\":\"%s\",\"reqNo\":\"%s\"}";
        try {
            String data = String.format(format, sno, reqNo);
            logger.info("CTMS接口【更新报关单号】。数据：" + data);
            return services.updateBGSno(data);
        } catch (Exception e) {
            logger.error("CTMS接口【更新报关单号】：未更新成功，捕获到异常。" + e.getMessage());
        }
        return "2";
    }
}
